package com.gin.kotlin.no_gay_alliance.activity

import android.content.Context
import android.content.Intent
import android.view.View
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingActivity
import com.gin.kotlin.no_gay_alliance.callback.RCallback
import com.gin.kotlin.no_gay_alliance.databinding.ActivityPrivilegeBinding
import com.gin.kotlin.no_gay_alliance.provider.ngaphp.PrivilegeProvider
import com.gin.kotlin.no_gay_alliance.webview.BbsCodeWebViewClient

class PrivilegeActivity : AbstractBindingActivity<ActivityPrivilegeBinding>(), RCallback<String, Long> {
    private var forumId: Long = 0L

    override fun onCreate() {
        val b = this.b ?: return
        b.webView.webViewClient = BbsCodeWebViewClient(this)
        request()
    }

    override fun onResume() {
        super.onResume()
        setToolbarTitle("版面权限")
    }

    override fun handleIntent(intent: Intent) {
        this.forumId = intent.getLongExtra(FORUM_ID, 0L).takeIf { it != 0L } ?: throw RuntimeException("必须提供版面id")
    }

    private fun request(ignoreCache: Boolean = false) {
        val b = this.b ?: return
        b.tvWarning.visibility = View.GONE
        PrivilegeProvider.getInstance().enqueue(forumId, ignoreCache = ignoreCache, callback = this)
    }

    companion object {
        private const val FORUM_ID = "fid"
        @JvmStatic
        fun start(context: Context, forumId: Long) = context.startActivity(Intent(context, PrivilegeActivity::class.java).putExtra(FORUM_ID, forumId))
    }

    override fun onSuccess(data: String, ignoreCache: Boolean) {
        val b = this.b ?: return
        b.webView.loadDataWithBaseURL(data)
    }

    override fun onError(errorMessage: String) {
        val b = this.b ?: return
        b.tvWarning.visibility = View.VISIBLE
        b.tvWarning.text = errorMessage
    }
}